package com.chinaunicom.emergency.util;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Log4j2
public class HttpClient {

    public static String getHtmlData(String url, Map<String, String> bodyPara, Map<String, String> headPara){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建参数队列
        List<NameValuePair> params = new ArrayList<>();
        Iterator it = bodyPara.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<String, String> item = (Map.Entry<String, String>)it.next();
            params.add(new BasicNameValuePair(item.getKey(), item.getValue()));
        }

        try {
            //参数转换为字符串
            String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(params, "UTF-8"));
            url += "?" + paramsStr;
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            Iterator headIt = headPara.entrySet().iterator();
            while (headIt.hasNext()){
                Map.Entry<String, String> item = (Map.Entry<String, String>)headIt.next();
                httpget.setHeader(new BasicHeader(item.getKey(), item.getValue()));
            }
            log.info("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {

                    // 打印响应内容长度
//                    log.info("Response content length: " + entity.getContentLength());
                    // 打印响应内容
//                    log.info("Response content: " + EntityUtils.toString(entity));
                    return EntityUtils.toString(entity,"UTF-8");
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static String postHtmlData(String url, String body, Map<String, String> headPara) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
//            log.info("post:请求URL：" + url + ", 请求参数：" + body);
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            if(headPara != null){
                Iterator headIt = headPara.entrySet().iterator();
                while (headIt.hasNext()) {
                    Map.Entry<String, String> item = (Map.Entry<String, String>) headIt.next();
                    httpPost.setHeader(new BasicHeader(item.getKey(), item.getValue()));
                }
            }
            if(StringUtils.isNotBlank(body)){
                StringEntity stringEntity = new StringEntity(body, "utf-8");
                stringEntity.setContentEncoding("UTF-8");
                stringEntity.setContentType("application/json");
                httpPost.setEntity(stringEntity);
            }

            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                String responseContent = EntityUtils.toString(entity, "UTF-8");
//                log.info("post:请求响应：" + responseContent);
                return responseContent;
            } finally {
                response.close();
                httpClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String putHtmlData(String url, String body, Map<String, String> headPara) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            log.info("put:请求URL：" + url + ", 请求参数：" + body);

            HttpPut httpPut = new HttpPut(url);
            httpPut.addHeader("Content-Type", "application/json;charset=utf-8");
            Iterator headIt = headPara.entrySet().iterator();
            while (headIt.hasNext()) {
                Map.Entry<String, String> item = (Map.Entry<String, String>) headIt.next();
                httpPut.setHeader(new BasicHeader(item.getKey(), item.getValue()));
            }
            StringEntity stringEntity = new StringEntity(body, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPut.setEntity(stringEntity);

            CloseableHttpResponse response = httpClient.execute(httpPut);
            try {
                HttpEntity entity = response.getEntity();
                String responseContent = EntityUtils.toString(entity, "UTF-8");
                return responseContent;
            } finally {
                response.close();
                httpClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  null;
    }


    public static String deleteHtmlData(String url, Map<String, String> headPara) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpDelete httpDelete = new HttpDelete(url);
            httpDelete.addHeader("Content-Type", "application/json;charset=utf-8");
            Iterator headIt = headPara.entrySet().iterator();
            while (headIt.hasNext()) {
                Map.Entry<String, String> item = (Map.Entry<String, String>) headIt.next();
                httpDelete.setHeader(new BasicHeader(item.getKey(), item.getValue()));
            }

            CloseableHttpResponse response = httpClient.execute(httpDelete);
            try {
                HttpEntity entity = response.getEntity();
                String responseContent = EntityUtils.toString(entity, "UTF-8");
                return responseContent;
            } finally {
                response.close();
                httpClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  null;
    }


}
